#!/bin/sh
#by BarryK 2006 for Puppy Linux v2.13+
#passed param is file to be converted.
#converts a .pet file to .tar.gz.
#131122 support xz compressed pets (see dir2pet, installpkg.sh)

chmod +w "$1" #make it writable.

FULLSIZE=`stat --format=%s "${1}"`
ORIGSIZE=`expr $FULLSIZE - 32`
##doing it this way have to remove dd stdout msg (preceded by a '+')...
##um, cut and sed are really intended for working on text files, may have to
##do this differently (in case have a corrupted file with non-char bytes on end)...
#MD5SUM="`dd if="${1}" bs=1 skip=${ORIGSIZE} 2>/dev/null | cut -f 1 -d '+' | sed -e 's/[^0-9a-zA-Z]/0/g'`" #md5sum to stdout.
#do it this indirect way instead...

#determine the compression, extend test to 'XZ'
file -b "$1" | grep -i -q "^xz" && EXT=xz || EXT=gz #131122 #140108 add -i for 'XZ'

dd if="${1}" of=/tmp/petmd5sum bs=1 skip=${ORIGSIZE} 2>/dev/null
sync
MD5SUM="`md5sum /tmp/petmd5sum | cut -f 1 -d ' '`"
#truncate is a little app I wrote. format: truncate newsize filename
truncate $ORIGSIZE "$1"
[ $? -ne 0 ] && exit 1
sync
#NEWMD5SUM="`md5sum "$1" | cut -f 1 -d ' '`"
md5sum "$1" | cut -f 1 -d ' ' > /tmp/newpetmd5sum
sync
#get rid of trailing newline char...
truncate 32 /tmp/newpetmd5sum
NEWMD5SUM="`md5sum /tmp/newpetmd5sum | cut -f 1 -d ' '`"
rm -f /tmp/petmd5sum
rm -f /tmp/newpetmd5sum
NEWNAME="`echo -n "${1}" | sed -e "s/\\.pet$/\\.tar\\.$EXT/g"`" #131122
mv -f $1 $NEWNAME
[ ! "$MD5SUM" = "$NEWMD5SUM" ] && exit 1
exit 0

